% ==== MugNet Demo =======
% T.-H. Chan, K. Jia, S. Gao, J. Lu, Z. Zeng, and Y. Ma,
% "PCANet: A simple deep learning baseline for image classification?"
% IEEE Trans. Image Processing, vol. 24, no. 12, pp. 5017-5032, Dec. 2015.

% Tsung-Han Chan [chantsunghan@gmail.com]
% Please email me if you find bugs, or have suggestions or questions!
% ========================
clear; clc;
addpath('./Utils');%add folder into search path
addpath('./Liblinear');
addpath('N:\RS\RollingGuidanceFilter_Matlab')
make;

ImgFormat = 'gray'; %'color' or 'gray'

%% Loading data from Indian Pines(training:20 every class)
load('./India/Indian_pines');
load('./India/Indian_pines_gt');
%% ==========Rolling Guidance Filter=================
indian_pines = RollingGuidanceFilter(indian_pines,3,0.05,10);

%% ===============Preprossing========================
[indian_data,indian_padding,train_num,zero_num,neibour_num,test_num]=...
    Mugnet_indian_preprossing(indian_pines,indian_pines_gt);

%% ==============Data Preparation====================
[TrnData_Spec,TrnLabels_Spec,TestData_Spec,TestLabels_Spec,...
    TrnData_Spat,TrnLabels_Spat,TestData_Spat,TestLabels_Spat]=...
    Mugnet_data_preparation(indian_data,indian_padding,train_num,zero_num,test_num);

%% PCANet parameters (they should be funed based on validation set; i.e., ValData & ValLabel)
% The parameters  used in the ISPRS paper
PCANet.NumStages = 2;
PCANet.NumFilters = [8 8];
PCANet.SpecPatchSize = [20 40 60];
PCANet.SpatPatchSize = [3 5 7];
PCANet.HistBlockSize = [7 7];
PCANet.BlkOverLapRatio = 0;
PCANet.Pyramid = [];

fprintf('\n ====== MugNet Parameters ======= \n')
PCANet
%% Mugnet Training with train+unlabeled samples
[models,spec_Weight,spat_Weight,PCANet_TrnTime,LinearSVM_TrnTime]=...
    Mugnet_Extraction_training(ImgFormat,TrnData_Spec,TrnLabels_Spec,TrnData_Spat,PCANet,train_num);

%% PCANet Feature Extraction and Testing
[testnum_result,Accuracy,ErRate,Averaged_TimeperTest,RecHistory]=...
    Mugnet_testing(ImgFormat,TestData_Spec,TestLabels_Spec,...
    TestData_Spat,test_num,spec_Weight,spat_Weight,models,PCANet);

%% Classification Result
fprintf('\n ===== Results of MugNet, followed by a linear SVM classifier =====');
fprintf('\n     S^2-PCANet training time: %.2f secs.', PCANet_TrnTime);
fprintf('\n     Linear SVM training time: %.2f secs.', LinearSVM_TrnTime);
fprintf('\n     Testing accuracy rate: %.2f%%',100*Accuracy);
fprintf('\n     Testing error rate: %.2f%%', 100*ErRate);
fprintf('\n     Average testing time %.2f secs per test sample. \n\n',Averaged_TimeperTest);

%% Rusult image
Result=zeros(145*145,1);
Result(train_num,1)=indian_data(train_num,end-1);
Result(neibour_num,1)=indian_data(neibour_num,end-1);
Result(test_num,1)=testnum_result;
ultimate=reshape(Result,145,145);
imwrite(uint8(ultimate),'result_fig_RGF.png')

